//
//  ProductDetailViewController.m
//  tangshantongjiAPP
//
//  Created by yuntai on 2018/4/4.
//  Copyright © 2018年 yuntai. All rights reserved.
//

#import "ProductDetailViewController.h"
#import "UIButton+TextImage.h"
#import <UIButton+WebCache.h>
#import <WBGImageEditor.h>
#import "ShowImagesView.h"

@interface ProductDetailViewController ()<WBGImageEditorDelegate,ShowImagesViewDelegate>
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *btnArrays;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *nameLabelArray;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomButtonHeight;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topLabelHeigth;
@property (nonatomic, assign) NSInteger counttype;
@property (weak, nonatomic) IBOutlet UIButton *uploadbtn;

@end

@implementation ProductDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.bottomButtonHeight.constant = kScreenBoundWidth/375.0*49;
    self.topLabelHeigth.constant = kScreenBoundWidth/375.0*49;
    
    UpLoadModelManager *manager = [UpLoadModelManager sharedInstance];
    if([manager.model.status isEqualToString:@"1"]){
        self.uploadbtn.hidden = YES;
        self.title = @"产品详情";
    }else{
        self.uploadbtn.hidden = NO;
        self.title = @"上传产品";
    }
    [self initUI];
    if (self.isFirstUp) {
        
        self.nameLabel.text = [@"产品名称: " stringByAppendingString:[UpLoadModelManager sharedInstance].model.name?:@""];
        
    }else{
        
        self.nameLabel.text = [@"产品名称: " stringByAppendingString:self.model.name];
        [self deltailApi];
    }
    weakself(self)
    [self setBackBtnEventHandler:^(id sender) {
        if (weakself.isFirstUp) {
            [weakself.navigationController popToViewController:[UpLoadModelManager sharedInstance].popvc  animated:YES];
        }else{
            [weakself.navigationController popViewControllerAnimated:YES];
        }
    }];
}
- (void)dealloc
{
    UpLoadModelManager *manager = [UpLoadModelManager sharedInstance];
    manager.model = nil;
    manager.popvc = nil;
    
}
/**上传操作*/
- (IBAction)uploadAction:(UIButton *)sender {
    //    if (self.isFirstUp) {
    UpLoadModelManager *manager = [UpLoadModelManager sharedInstance];
    NSArray *temparray = [NSArray arrayWithObjects:manager.model.img1?:@"", manager.model.img2?:@"",manager.model.img3?:@"",manager.model.img4?:@"",manager.model.img5?:@"", nil];
    [HUDManager showLoadingHUDView:self.view];
    weakself(self)
    [NetWork PostUpLoadImageWithImages:temparray withID:manager.model.modelid successBlock:^(NSString *imagePath) {
        
        [weakself saveApi];
        
    } FailureBlock:^(NSString *msg) {
        [HUDManager showWarningWithText:msg];
    } errorBlock:^(id error) {
        
    }];
    //    }
}

- (IBAction)btnActions:(UIButton *)sender {
    
    self.counttype = sender.tag;
    ShowImagesView * showImage = [[ShowImagesView alloc] init];
    showImage.currentIndex = 0;
    showImage.imagesPath = @[sender.imageView.image];
    showImage.selectView = sender;
    showImage.delegate = self;
    if(sender.tag == 2 || sender.tag == 3){
        showImage.midBtn.hidden = NO;
    }else{
        showImage.midBtn.hidden = YES;
    }
    [showImage present];
    return;
}

#pragma mark - showimageview delegate
/**点击修改*/
-(void)leftShowImagesView:(ShowImagesView *)view{
    [view dismiss];
    __block  UpLoadModelManager *manager = [UpLoadModelManager sharedInstance];
    
    weakself(self)
    [[CameraTakeMamanger sharedInstance] cameraSheetInController:self handler:^(UIImage *image, NSString *imagePath) {
        if(weakself.counttype == 2 || weakself.counttype == 3){
            WBGImageEditor *editor = [[WBGImageEditor alloc] initWithImage:image  delegate:weakself];
            [weakself presentViewController:editor animated:YES completion:nil];
        }else{
            [manager.model setValue:image forKey:[NSString stringWithFormat:@"img%ld",weakself.counttype+1]];
            UIButton *tempbtn = weakself.btnArrays[weakself.counttype];
            [tempbtn setImage:image forState:UIControlStateNormal];
        }
    } cancelHandler:^{
        
    }];
}
/**点击涂鸦*/
-(void)midShowImagesView:(ShowImagesView *)view{
    [view dismiss];
    UIButton *tempbtn = self.btnArrays[self.counttype];
    WBGImageEditor *editor = [[WBGImageEditor alloc] initWithImage:tempbtn.imageView.image  delegate:self];
    [self presentViewController:editor animated:YES completion:nil];
    
    
}
#pragma mark - WBGImageEditorDelegate
/**涂鸦完成*/
- (void)imageEditor:(WBGImageEditor *)editor didFinishEdittingWithImage:(UIImage *)image {
    
    UpLoadModelManager * manager = [UpLoadModelManager sharedInstance];
    if (self.counttype == 2){
        manager.model.img3 = image;
    }else if ( self.counttype == 3){
        manager.model.img4 = image;
    }
    UIButton *tempbtn = self.btnArrays[self.counttype];
    [tempbtn setImage:image forState:UIControlStateNormal];
    
    [editor.presentingViewController dismissViewControllerAnimated:YES completion:nil];
}

- (void)imageEditorDidCancel:(WBGImageEditor *)editor {
    
}
- (void)initUI{
    
    NSArray *nameArray = [NSArray arrayWithObjects:@"特征描述表",@"报表照片",@"第一张凭证照片",@"第二张凭证照片",@"台账照片", nil];
    NSArray *iamgeNameArray = [NSArray arrayWithObjects:@"addimageIcon",@"addimageIcon",@"addimageIcon",@"addimageIcon",@"addimageIcon", nil];
    NSMutableArray *tempimagearray = [NSMutableArray array];
    if (self.isFirstUp) {
        [tempimagearray addObject:[UpLoadModelManager sharedInstance].model.img1?:@""];
        [tempimagearray addObject:[UpLoadModelManager sharedInstance].model.img2?:@""];
        [tempimagearray addObject:[UpLoadModelManager sharedInstance].model.img3?:@""];
        [tempimagearray addObject:[UpLoadModelManager sharedInstance].model.img4?:@""];
        [tempimagearray addObject:[UpLoadModelManager sharedInstance].model.img5?:@""];
        
    }
    
    [self.btnArrays enumerateObjectsUsingBlock:^(UIButton *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        if (idx == 5) {
            obj.hidden = YES;
            
        }
        UILabel *l = self.nameLabelArray[idx];
        if (IS_IPHONE5) {
            l.font = [UIFont systemFontOfSize:14];
        }
        l.text = nameArray[idx];
        
        obj.layer.cornerRadius = 2.2f;
        obj.layer.masksToBounds = YES;
        if (self.isFirstUp) {
            if (idx == 0 && [UpLoadModelManager sharedInstance].model.imageurl1 != nil) {
                obj.enabled = NO;
                [obj sd_setImageWithURL:[NSURL URLWithString:[UpLoadModelManager sharedInstance].model.imageurl1] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"ic_default_img"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                    obj.enabled = YES;
                }];
            }else{
                [obj setImage:tempimagearray[idx] forState:UIControlStateNormal];
            }
        }else{
            [obj setImage:[UIImage imageNamed:iamgeNameArray[idx]] forState:UIControlStateNormal];
            
        }
    }];
    
}


- (void)saveApi{
    UpLoadModelManager *manager = [UpLoadModelManager sharedInstance];
    NSMutableDictionary *parma= [NSMutableDictionary dictionary];
    [parma setValue:manager.model.imageurl1 forKey:@"img1"];
    [parma setValue:manager.model.imageurl2 forKey:@"img2"];
    [parma setValue:manager.model.imageurl3 forKey:@"img3"];
    [parma setValue:manager.model.imageurl5 forKey:@"img4"];
    [parma setValue:manager.model.imageurl4 forKey:@"img5"];
    [parma setValue:manager.model.name forKey:@"name "];
    [parma setValue:manager.model.modelid forKey:@"id"];
    [parma setValue:@(manager.model.type) forKey:@"type"];
    [parma setValue:kTokenID forKey:@"token"];
    
    [HUDManager showLoadingHUDView:self.view];
    weakself(self)
    [NetWork PostNetWorkWithUrl:@"api/pro/save.ajax" with:parma successBlock:^(NSDictionary *dic) {
        [HUDManager showWarningWithText:@"发布成功!"];
        [[NSNotificationCenter defaultCenter]postNotificationName:@"updateViewNoti" object:nil];
        [weakself.navigationController popToViewController:[UpLoadModelManager sharedInstance].popvc  animated:YES];
        
    } FailureBlock:^(NSString *msg) {
        
    } errorBlock:^(id error) {
        
    }];
    
}

- (void)deltailApi{
    UpLoadModelManager *manager = [UpLoadModelManager sharedInstance];
    NSMutableDictionary *parma= [NSMutableDictionary dictionary];
    [parma setValue:manager.model.modelid forKey:@"id"];
    [parma setValue:@(manager.model.type) forKey:@"type"];
    [parma setValue:kTokenID forKey:@"token"];
    [HUDManager showLoadingHUDView:self.view];
    weakself(self)
    [NetWork PostNetWorkWithUrl:@"api/pro/getOne.ajax" with:parma successBlock:^(NSDictionary *dic) {
        NSDictionary *tempdic = dic[@"data"][@"product"];
        weakself.model = [CommonModel mj_objectWithKeyValues:tempdic];
        NSString *temp ;
        if(weakself.model.img4 && weakself.model.img5){
            temp = weakself.model.img4;
            weakself.model.img4 = weakself.model.img5;
            weakself.model.img5 = temp;
        }
        [weakself.btnArrays enumerateObjectsUsingBlock:^(UIButton *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            NSString *temstr = [weakself.model valueForKey:[NSString stringWithFormat:@"img%lu",idx+1]];
            obj.enabled = NO;
            [obj sd_setImageWithURL:[NSURL URLWithString:temstr] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"ic_default_img"] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                obj.enabled = YES;
            }];
            
        }];
        
        
    } FailureBlock:^(NSString *msg) {
        
    } errorBlock:^(id error) {
        
    }];
}
@end
